<template>
  <div class="admin-chat">
    <div class="chat-layout">
      <div class="user-list">
        <h3>用户列表</h3>
        <div
          v-for="user in userList"
          :key="user.userId"
          :class="['user-item', { active: selectedUser?.userId === user.userId }]"
          @click="selectUser(user)"
        >
          <div class="avatar-container">
            <el-avatar :size="32" :src="user.avatar">
              {{ (user.nickName || user.userName).charAt(0) }}
            </el-avatar>
            <!-- 未读消息提醒 -->
            <div v-if="user.unreadCount > 0" class="unread-badge">
              {{ user.unreadCount > 99 ? '99+' : user.unreadCount }}
            </div>
          </div>
          <span>{{ user.nickName || user.userName }}</span>
        </div>
      </div>
      
      <div class="chat-window">
        <div v-if="selectedUser" class="chat-content">
          <div class="chat-header">
            <h4>{{ selectedUser.nickName || selectedUser.userName }}</h4>
          </div>
          
          <div class="messages" ref="messagesContainer">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message', message.senderId === userStore.id ? 'sent' : 'received']"
            >
              <!-- 头像区域 -->
              <div class="message-avatar">
                <el-avatar 
                  :size="36" 
                  :src="message.senderId === userStore.id ? userStore.avatar : selectedUser.avatar"
                >
                  {{ message.senderId === userStore.id ? 
                     (userStore.nickName || userStore.name).charAt(0) : 
                     selectedUser.nickName.charAt(0) }}
                </el-avatar>
              </div>
              
              <!-- 消息内容区域 -->
              <div class="message-wrapper">
                <div class="message-content">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.sendTime) }}</div>
              </div>
            </div>
          </div>
          
          <div class="input-area">
            <el-input
              v-model="messageText"
              type="textarea"
              :rows="2"
              placeholder="输入消息..."
            />
            <el-button type="primary" @click="sendMessage" :disabled="!messageText.trim()">
              发送
            </el-button>
          </div>
        </div>
        
        <div v-else class="no-chat">
          <p>请选择用户开始聊天</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { sendMessage as sendMessageApi, getChatHistory, getChatUserList, markMessagesAsRead } from '@/api/hk/chat'

const userStore = useUserStore()
const selectedUser = ref(null)
const messages = ref([])
const messageText = ref('')
const messagesContainer = ref(null)

const userList = ref([])

// 加载所有其他用户列表
const loadUserConversations = async () => {
  try {
    const response = await getChatUserList()
    if (response.code === 200) {
      userList.value = response.data || []
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

const selectUser = async (user) => {
  selectedUser.value = user
  messages.value = []
  
  // 标记消息为已读
  if (user && user.userId) {
    try {
      await markMessagesAsRead(user.userId)
      // 更新本地未读消息数
      const userInList = userList.value.find(u => u.userId === user.userId)
      if (userInList) {
        userInList.unreadCount = 0
      }
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 加载聊天历史
  if (user && user.userId) {
    try {
      const response = await getChatHistory(user.userId)
      if (response.code === 200) {
        messages.value = response.data || []
        // 滚动到底部
        nextTick(() => {
          scrollToBottom()
        })
      }
    } catch (error) {
      console.error('加载聊天历史失败:', error)
      ElMessage.error('加载聊天历史失败')
    }
  }
}

const sendMessage = async () => {
  if (!messageText.value.trim() || !selectedUser.value) return
  
  try {
    const messageData = {
      receiverId: selectedUser.value.userId,
      content: messageText.value.trim(),
      messageType: 1
    }
    
    console.log('发送消息数据:', messageData)
    
    // 先添加消息到本地列表（发送者视角）
    const newMessage = {
      id: Date.now(), // 临时ID
      senderId: userStore.id,
      receiverId: selectedUser.value.userId,
      content: messageText.value.trim(),
      sendTime: new Date(),
      senderName: userStore.nickName || userStore.name,
      senderAvatar: userStore.avatar
    }
    
    messages.value.push(newMessage)
    messageText.value = ''
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
    
    // 发送消息到后端
    const response = await sendMessageApi(messageData)
    console.log('发送消息响应:', response)
    
    if (response.code === 200) {
      ElMessage.success('消息发送成功')
    } else {
      ElMessage.error(response.message || '消息发送失败')
      // 如果发送失败，从本地列表中移除消息
      const index = messages.value.findIndex(msg => msg.id === newMessage.id)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('消息发送失败，请检查网络连接')
    // 如果发送失败，从本地列表中移除消息
    const index = messages.value.findIndex(msg => msg.content === messageText.value.trim())
    if (index > -1) {
      messages.value.splice(index, 1)
    }
  }
}

const scrollToBottom = () => {
  const messagesContainer = document.querySelector('.messages')
  if (messagesContainer) {
    messagesContainer.scrollTop = messagesContainer.scrollHeight
  }
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleTimeString('zh-CN')
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

onMounted(() => {
  // 加载用户会话列表
  loadUserConversations()
  
  // 初始化WebSocket连接
  if (userStore.id) {
    // 使用环境变量或默认值构建WebSocket URL
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsHost = import.meta.env.VITE_APP_BASE_API ? 
      window.location.host + import.meta.env.VITE_APP_BASE_API.replace('/dev-api', '') : 
      'localhost:8080'
    const ws = new WebSocket(`${wsProtocol}//${wsHost}/api/websocket/chat/${userStore.id}`)
    
    ws.onopen = () => {
      console.log('管理员WebSocket连接已建立')
    }
    
    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        console.log('管理员收到WebSocket消息:', message)
        
        // 检查消息是否应该显示在当前聊天窗口中
        // 修复：确保管理员发送的消息也能显示
        if (message.senderId === selectedUser.value?.userId || 
            message.receiverId === selectedUser.value?.userId) {
          
          // 检查消息是否已经存在，避免重复显示
          const messageExists = messages.value.some(msg => 
            msg.id === message.id || 
            (msg.senderId === message.senderId && 
             msg.receiverId === message.receiverId && 
             msg.content === message.content && 
             Math.abs(new Date(msg.sendTime) - new Date(message.sendTime)) < 1000)
          )
          
          if (!messageExists) {
            // 确保消息有必要的字段
            const newMessage = {
              id: message.id || Date.now(),
              senderId: message.senderId,
              receiverId: message.receiverId,
              content: message.content,
              sendTime: message.sendTime || new Date(),
              senderName: message.senderName,
              senderAvatar: message.senderAvatar,
              receiverName: message.receiverName,
              receiverAvatar: message.receiverAvatar
            }
            
            console.log('添加新消息到列表:', newMessage)
            
            // 添加到消息列表
            messages.value.push(newMessage)
            
                         // 自动滚动到底部
             nextTick(() => {
               scrollToBottom()
             })
          }
        }
        
        // 更新未读消息数
        updateUnreadCount(message.senderId, message.receiverId)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }
  }
})

// 更新未读消息数
const updateUnreadCount = (senderId, receiverId) => {
  if (receiverId === userStore.id) {
    // 当前用户收到消息，更新发送者的未读消息数
    const user = userList.value.find(u => u.userId === senderId)
    if (user) {
      user.unreadCount = (user.unreadCount || 0) + 1
    }
  }
}
</script>

<style scoped>
.admin-chat {
  height: 100vh;
  max-height: 100vh;
}

.chat-layout {
  display: flex;
  height: 100vh;
  gap: 20px;
}

.user-list {
  width: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: white;
  height: 100vh;
  overflow-y: auto;
}

.user-list h3 {
  margin-bottom: 16px;
  color: #333;
  position: sticky;
  top: 0;
  background: white;
  padding: 8px 0;
  z-index: 10;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 8px;
}

.user-item:hover {
  background: #f5f5f5;
}

.user-item.active {
  background: #e6f7ff;
}

.user-item span {
  margin-left: 8px;
}

.avatar-container {
  position: relative;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  min-width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
  box-sizing: border-box;
}

.chat-window {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
  display: flex;
  flex-direction: column;
  height: 100vh;
  min-height: 100vh;
  max-height: 100vh;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.chat-header h4 {
  margin: 0;
  color: #333;
}

.messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f5f5f5;
  min-height: 300px;
  /* 确保滚动条样式美观 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f5f5f5;
}

/* 自定义滚动条样式 */
.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: #f5f5f5;
}

.messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.message {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.message.sent {
  flex-direction: row-reverse;
  gap: 8px;
}

.message.received {
  flex-direction: row;
  gap: 8px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 480px;
  min-width: 120px;
}

.message-content {
  padding: 10px 14px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
  white-space: normal;
  overflow-wrap: break-word;
  word-wrap: break-word;
  max-width: 480px;
  box-sizing: border-box;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: center;
}

.message.sent .message-content {
  background: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.received .message-content {
  background: white;
  color: #333;
  border: 1px solid #e4e7ed;
  border-bottom-left-radius: 4px;
}

.message.sent .message-time {
  text-align: right;
}

.message.received .message-time {
  text-align: left;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-area .el-textarea {
  flex: 1;
}

.no-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-window {
    height: 100vh;
    min-height: 100vh;
  }
  
  .messages {
    min-height: 200px;
  }
  
  .user-list {
    width: 150px;
    height: 100vh;
  }
  
  .chat-layout {
    gap: 10px;
  }
}

/* 确保在小屏幕上滚动功能正常 */
@media (max-width: 480px) {
  .chat-window {
    height: 100vh;
    min-height: 100vh;
  }
  
  .messages {
    min-height: 150px;
  }
}
</style>
